package com.newlink.building.record

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.Window
import com.newlink.building.library_rino.ConnectionController
import com.newlink.building.common_base.base.NL_BaseActivity
import com.newlink.building.common_base.base.BaseApplication
import com.newlink.building.common_base.event.AlarmNotifyBean
import com.newlink.building.common_base.event.AlarmNotifyHandleBean
import com.newlink.building.common_base.event.HandleAlarmActionRequest
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.Base_SendMqttMsgEvent
import com.newlink.building.common_base.event.TYPE_APP_MQTT_NOTIFY_ALARM_NOTIFY
import com.newlink.building.common_base.event.TYPE_POPOVER_CANCEL_ALARM_NOTIFY
import com.newlink.building.common_base.ext.getBoolean
import com.newlink.building.common_base.utils.Base_VibratorHelper
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.manager.Module_Phone_VoipController
import com.newlink.building.record.databinding.ActivityGlobalPopoverBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * @author wangyang
 * @date 2023/5/12
 * @description 全局弹窗页面——警报
 */
class Module_Record_GlobalPopoverActivityNL : NL_BaseActivity() {

    private lateinit var alarmBean: AlarmNotifyBean.Data
    private var sessionId: String = ""
    private var fromRecord: Boolean = false
    private var isAlarmHandle: Boolean = false
    private val fvlVibratorHelper: Base_VibratorHelper by lazy {
        Base_VibratorHelper.getInstance(
            applicationContext
        )
    }

    companion object {
        /**
         * 对外开放统一入口
         *
         * @param context
         * @param data     AlarmBean
         */
        fun startSelf(
            context: Context?,
            data: AlarmNotifyBean.Data,
            sessionId: String = "",
            fromRecord: Boolean = false,
        ) {
            val intent = Intent(context, Module_Record_GlobalPopoverActivityNL::class.java)
            intent.putExtra("AlarmBean", data)
            intent.putExtra("sessionId", sessionId)
            intent.putExtra("fromRecord", fromRecord)
            context?.startActivity(intent)
        }

        fun startSelfFront(context: Context?) {
            val intent = Intent(context, Module_Record_GlobalPopoverActivityNL::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
            context?.startActivity(intent)
        }
    }

    private lateinit var mBinding: ActivityGlobalPopoverBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityGlobalPopoverBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        super.onCreate(savedInstanceState)
    }

    override fun initData() {
    }

    override fun initView() {
        alarmBean = intent.getSerializableExtra("AlarmBean") as AlarmNotifyBean.Data
        sessionId = intent.getStringExtra("sessionId")!!
        fromRecord = intent.getBoolean("fromRecord")
        if (alarmBean == null) {
            finish()
        }
        //是否处于通话中
        var duringCall = isDuringCall()

        if (alarmBean.handle == 1) {
            //已处理
            mBinding.tvTitle.text = getString(R.string.alarm_title_processed)
            mBinding.btnDispose.visibility = View.GONE
//            vibrator.cancel()
            fvlVibratorHelper.stopVibration(alarmBean.id)
        } else {
            //未处理
            mBinding.tvTitle.text = getString(R.string.alarm_title)
            mBinding.btnDispose.visibility = View.VISIBLE
            if (alarmBean.alarmType == 2) {
//                mBinding.btnDispose.text = if(duringCall) getString(R.string.dialog_exit_confirm) else getString(R.string.dispose_dialog_watch)
                mBinding.btnDispose.text = getString(R.string.dispose_dialog_watch)
            } else {
                mBinding.btnDispose.text = getString(R.string.dispose_dialog_custom)
            }
            if (!fromRecord) {
//                vibrator.vibrate(longArrayOf(0, 1000, 300), 0)
                fvlVibratorHelper.startVibration(alarmId = alarmBean.id)
            }
        }
        val desc = when (alarmBean.alarmType) {
            1 -> {
                resources.getString(R.string.alarm_type_tamper)
            }

            2 -> {
                resources.getString(R.string.function_move_detection)
            }

            else -> {
                alarmBean.alarmDesc
            }
        }
        mBinding.tvDescribeType.text = desc
        mBinding.tvDescribe.text = "${alarmBean.devName}"
        mBinding.tvTime.text = alarmBean.alarmTime

        mBinding.btnCancel.setOnClickListener {
            EventBus.getDefault().post(MessageEvent(TYPE_POPOVER_CANCEL_ALARM_NOTIFY, alarmBean.id))
            fvlVibratorHelper.stopVibration(alarmBean.id)
            finish()
        }
        mBinding.btnDispose.setOnClickListener {
            val dataAlarm = HandleAlarmActionRequest.Data(alarmBean.id)
            val handleAlarmActionRequest = HandleAlarmActionRequest(
                msgId = "",
                data = dataAlarm
            )
            if (mBinding.btnDispose.text == getString(R.string.dispose_dialog_watch)) {
                duringCall = isDuringCall()
            }
//            sendHandleAlarmActionRequest(handleAlarmActionRequest)
            if (alarmBean.alarmType == 2) {
                if (duringCall) {
                    updateSateHangupState()
                    duringCall = false
                } else {
                    isAlarmHandle = true
                    sendHandleAlarmActionRequest(handleAlarmActionRequest)
                    if (Module_Phone_VoipController.get().isFirstCallInMonitor()) {
                        Module_Phone_VoipController.get().hangUp()
                        GlobalScope.launch(Dispatchers.IO) {
                            delay(1200)
                            withContext(Dispatchers.Main) {
                                makeMonitorCall()
                            }
                        }
                        finish()

                    } else {
                        Module_Phone_VoipController.get().hangUp()
                        makeMonitorCall()
                    }
                }
            } else {
                sendHandleAlarmActionRequest(handleAlarmActionRequest)
                mBinding.tvTitle.text = getString(R.string.alarm_title_processed)
                mBinding.btnDispose.visibility = View.GONE
//            vibrator.cancel()
            }
        }
    }

    private fun makeMonitorCall() {
        NLog.d("[jake] => [GlobalPopoverActivity] makeMonitorCall alarmBean:$alarmBean")
        ConnectionController.getInstance(applicationContext).clearCacheAtBeginning()
        if (!alarmBean.sip.isNullOrEmpty()) {
            Module_Phone_VoipController.get().makeMonitorCall(alarmBean.sip!!, alarmBean.devName)
        } else {
            val deviceData = BaseApplication.getDeviceDataByMac(alarmBean.mac)
            NLog.d("[jake] => [GlobalPopoverActivity] makeMonitorCall deviceData:$deviceData")
            deviceData?.let {
                Module_Phone_VoipController.get().makeMonitorCall(it.aid.toString(), it.devName.orEmpty())
            }
        }
        finish()
    }

    private fun isDuringCall(): Boolean {
        return Module_Phone_VoipController.get().isCallingState()
    }

    private fun sendHandleAlarmActionRequest(handleAlarmActionRequest: HandleAlarmActionRequest) {
        EventBus.getDefault().post(Base_SendMqttMsgEvent(userId, handleAlarmActionRequest))
        fvlVibratorHelper.stopVibration(alarmBean.id)
    }

    private fun updateSateHangupState() {
        mBinding.tvMessage.text = getString(R.string.message_hangup_switch_monitoring)
        mBinding.btnDispose.text = getString(R.string.dialog_exit_confirm)
        mBinding.tvMessage.visibility = View.VISIBLE
        mBinding.tvDescribeLayout.visibility = View.INVISIBLE
    }

    override fun onBackPressed() {
//        super.onBackPressed()
    }

    override fun onDestroy() {
        super.onDestroy()
//        vibrator.cancel()
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAlarmHandleNotifyEvent(event: MessageEvent) {
        if (event.msgType == TYPE_APP_MQTT_NOTIFY_ALARM_NOTIFY) {
            val alarmNotifyHandleBean = event.msgContent as AlarmNotifyHandleBean?
            NLog.e("[jake] => [GlobalPopoverActivity] 收到信息 :  TYPE_APP_MQTT_NOTIFY_ALARM_NOTIFY....$alarmNotifyHandleBean")
            alarmNotifyHandleBean?.let { handleBean ->
                val data = handleBean.data
                if (data.id == alarmBean.id) {
                    if (isAlarmHandle) {
                        mBinding.contentLayout.visibility = View.GONE
                    }
//                    showToast(getString(R.string.handle_notify_content))
//                    NLog.e("[jake] => [GlobalPopoverActivity] 处理消息 :  安防通知弹窗 消失....")
//                    GlobalPopoverActivity@this.finish()

                    mBinding.tvTitle.text = getString(R.string.alarm_title_processed)
                    mBinding.tvDescribeLayout.visibility = View.VISIBLE
                    mBinding.tvMessage.visibility = View.GONE
                    mBinding.btnDispose.visibility = View.GONE
//                    vibrator.cancel()
                    fvlVibratorHelper.stopVibration(data.id)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        //用户主动锁屏回来要继续震动
        if (fvlVibratorHelper.hasVibration()) {
            fvlVibratorHelper.activeVibration()
        }
    }
}